"use strict"

let CBGLP_Claimable          = "0"
let CBGLP_RewardsSeconds     = "0"
let CBGLP_RewardTime         =  0

let balance_cb   = 0
let liquidity_cb = 0

function onLogin()
{
    onInitLiquidity();
    GLP_ClaimableLoop();
    CheckApproveLoop();
}

function GetContractCBGLP()
{
    return new window._ethers.Contract(Contract_CBGLP, Contract_GamingLP_Abi, Helper.provider.getSigner());
}

async function doApproveToCBGLP(contractAddr,input_amount,decimals)
{
    const amount = window._ethers.utils.parseUnits(input_amount, decimals)
    const contract = new window._ethers.Contract(contractAddr, Contract_ERC20_Abi, Helper.provider.getSigner());          
    var tx = await contract.approve(Contract_CBGLP,amount);
    var rel = await tx.wait();
    return new Promise((resolve, reject) => {
        resolve(rel.status);
    })
}

async function onInitLiquidity()
{
    var contractCB     = GetContractERC20(Contract_CB);
    var contractCBGLP  = GetContractCBGLP();
    
    await RefreshRewardsSeconds();
    await RefreshAllow();

    balance_cb = await contractCB.balanceOf(Helper.addressCur);
    balance_cb = window._ethers.utils.formatUnits(balance_cb, Contract_Decimals)
    balance_cb = Helper.Fix2(balance_cb)

    liquidity_cb = await contractCBGLP.balanceOf(Helper.addressCur);
    liquidity_cb = window._ethers.utils.formatUnits(liquidity_cb, Contract_Decimals)
    liquidity_cb = Helper.Fix2(liquidity_cb)

    $("#balance_cb").html("Balance: " + balance_cb );
    $("#UniV3_Liquidity").html("Liquidity: " + liquidity_cb );


    try{
        var rel  = await contractCBGLP["getfreeAmount(address)"](Helper.addressCur);
    }
    catch(e)
    {

    }

    await RefreshYourDeposits();
}

async function RefreshRewardsSeconds()
{
    try{
        var contract = GetContractCBGLP();
        CBGLP_RewardsSeconds = await contract.GetRewardsSeconds(Helper.addressCur);
        CBGLP_RewardsSeconds = window._ethers.utils.formatUnits(CBGLP_RewardsSeconds, Contract_Decimals)
        CBGLP_RewardsSeconds  = Helper.Fix(CBGLP_RewardsSeconds)

        CBGLP_Claimable = await contract["GetRewards(address)"](Helper.addressCur);
        CBGLP_Claimable = window._ethers.utils.formatUnits(CBGLP_Claimable, Contract_Decimals)
        CBGLP_Claimable = Helper.Fix(CBGLP_Claimable)

        CBGLP_RewardTime = Date.now();
    }
    catch(e)
    {
    }
}

async function onclickApprove(id)
{
    if(id=="univ3_input_cb"){
        var amount = $("#univ3_input_cb").val();
        var status = await doApproveToCBGLP(Contract_CB,balance_cb,Contract_Decimals);
        if(status==1) {
            ShowToastr("Success","Approve CB");
            GLP_allowCB = amount;
            return;
        }
    }
    setTimeout("onInitLiquidity()", 5000);
    setTimeout("onInitLiquidity()", 15000); 
}

let GLP_allowCB = -1;
async function RefreshAllow()
{
    var contractCB    = GetContractERC20(Contract_CB);
    if(GLP_allowCB==-1){
        GLP_allowCB = await contractCB.allowance(Helper.addressCur,Contract_CBGLP)
        GLP_allowCB = window._ethers.utils.formatUnits(GLP_allowCB, Contract_Decimals)
    }
}


function uni_input_change(event){
    var inputID = event.currentTarget.id;
    var value   = $(event.currentTarget).val();
    if(inputID=="univ3_input_cb"){
        if( Helper.isGreater(value,balance_cb) || value=="00" ){
            $(event.currentTarget).val(balance_cb);
            value = balance_cb;
        }

        $("#univ3_input_usdt").val( Helper.Fix2(value) );
    }
    else
    if(inputID=="input_liquidity"){
        if( Helper.isGreater(value,liquidity_cb) || value=="00" ){
            $(event.currentTarget).val(liquidity_cb);
            value = liquidity_cb;
        }
    }

}


async function CheckApproveLoop()
{
    while(true){
        if(Helper.addressCur!=null){

            var btn_Approve_CB = false;

            var uu = $("#univ3_input_cb").val();
            if(!isNaN(uu)&&uu!=""&&uu!="0"){
                if( Helper.isLessThanOrEqualTo(uu,GLP_allowCB) ){
                    $("#btn_Approve_CB").addClass("d-none");
                    btn_Approve_CB = false;
                }
                else {
                    $("#btn_Approve_CB").removeClass("d-none");
                    btn_Approve_CB = true;
                }
            }else{
                $("#btn_Approve_CB").addClass("d-none");
                btn_Approve_CB = false;
            }

            if(btn_Approve_CB==false&&!isNaN(uu)&&uu!=""&&uu!="0"){
                $("#btn_Approve_Deposit").removeClass("disabled");
            }
            else{
                $("#btn_Approve_Deposit").addClass("disabled");
            }

        }
        await Helper.sleep(1000);
    }
}


async function GLP_ClaimableLoop(){
    while(true){
        var addValue =  Helper.Mul( CBGLP_RewardsSeconds,  ((Date.now() - CBGLP_RewardTime)/1000).toString()  )
        addValue = Helper.Add(CBGLP_Claimable , addValue );
        $("#CBGLP_Claimable").html( Helper.Fix8(addValue) );
        await Helper.sleep(100);
    }
}


async function onclickDeposit(){
    $("#btn_Approve_Deposit").attr('disabled', true);    
    setTimeout("$('#btn_Approve_Deposit').attr('disabled', false);", 5000);

    var input_amountCB = Helper.FixDecimal($("#univ3_input_cb").val(),Contract_Decimals);
    var contract = GetContractCBGLP();
    const amountCB = window._ethers.utils.parseUnits(input_amountCB, Contract_Decimals)
    
    try{
        var tx  = await contract.addLiquidity(Helper.addressCur, amountCB, Helper.addressCur , 0, 0); // token0是CB
        var rel = await tx.wait();
        if(rel.status==1){
            $("#univ3_input_cb").val("0");
            ShowToastr("Success","Add Liquidity");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);
        setTimeout("onInitLiquidity()", 35000);
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }
}

async function onclickWithdrawAll(){
    $("#GPL_btn_Withdraw_All").attr('disabled', true);    
    setTimeout("$('#GPL_btn_Withdraw_All').attr('disabled', false);", 5000);

    var contract = GetContractCBGLP();
    var liquidity  = await contract.balanceOf(Helper.addressCur);
    if(liquidity.toString()=="0") return;

    try{
        var tx  = await contract.removeLiquidity(Helper.addressCur, liquidity, 0, 0 );
        var rel = await tx.wait();
        if(rel.status==1){
            ShowToastr("Success","Withdraw All");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);         
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }


}

async function onclickWithdraw(){
    $("#btn_Withdraw").attr('disabled', true);    
    setTimeout("$('#btn_Withdraw').attr('disabled', false);", 5000);

    var input_liquidity = $("#input_liquidity").val();
    if(input_liquidity.toString()=="0") return;
    if(input_liquidity==liquidity_cb) return GLP_onclickWithdrawAll();
    
    var contract = GetContractCBGLP();
    input_liquidity = window._ethers.utils.parseUnits(input_liquidity, Contract_Decimals)

    try{
        var tx  = await contract.removeLiquidity(Helper.addressCur, input_liquidity, 0, 0 );
        var rel = await tx.wait();
        if(rel.status==1){
            $("#input_liquidity").val(0);
            ShowToastr("Success","Withdraw");
        }
        setTimeout("onInitLiquidity()", 5000);
        setTimeout("onInitLiquidity()", 15000);         
    }
    catch(e)
    {
        if(e.code=="UNPREDICTABLE_GAS_LIMIT") {
            ShowToastrError("Error","Network congestion, please try again later");
        }
    }
}

async function onclickClaim(){
    
    var contract = GetContractCBGLP();
    var tx  = await contract.Claim(Helper.addressCur);
    var rel = await tx.wait();
    if(rel.status==1){
        ShowToastr("Success","Claim All");
    }
    setTimeout("RefreshRewardsSeconds()", 3000);
    setTimeout("RefreshRewardsSeconds()", 10000);

}


function onclickMax(e){
    if(e=="univ3_input_cb"){
        $("#"+e).val(balance_cb);
    }
    else
    if(e=="input_liquidity"){
        $("#"+e).val(liquidity_cb);
    }

}

function AddCBGToMetamask(){
    AddToMetamask(Contract_CBG,"CBG",Contract_Decimals,"https://chainbet.tech/my_imgae/CBG.png")

}

let amountUsdt = "0";
async function RefreshYourDeposits()
{
    var contractCB   = GetContractERC20(Contract_CB);
    var totalSupplyCB = "0";
    try{
        totalSupplyCB  = await contractCB.balanceOf(Contract_CBGLP);
        totalSupplyCB  = Helper.Fix2(window._ethers.utils.formatUnits(totalSupplyCB, Contract_Decimals));
        }
    catch(e)
    {
    }

    var contractCBG   = GetContractCBGLP();
    var totalSupply = 0;
    try{    
        totalSupply = await contractCBG.totalSupplyToken();
        totalSupply = Helper.Fix2(window._ethers.utils.formatUnits(totalSupply, Contract_Decimals));
    }
    catch(e)
    {
    }

    var amountCB = 0;
    if(totalSupply!="0"){
        amountCB = Helper.Div(Helper.Mul(liquidity_cb,totalSupplyCB),totalSupply);
    }
    $("#Your-Deposits").html(""+ Helper.Fix2(amountCB) );

    var revenue = "0";
    if(totalSupply!="0"){
        revenue = Helper.Div(Helper.Mul(liquidity_cb,"10000"),totalSupply);
    }
    $("#Daily-Revenue").html( Helper.Fix2(revenue) );

}



(function($) {
    "use strict"



})(jQuery);


